<template>
  <view class="container">
    <view class="fee-pane-content">
      <ve-form ref="formRef" :model="feeForm" :rules="rules">
        <view class="fee-stage-item" v-for="(item, index) in feeForm.orderFee" :key="index">
          <ve-card
            :title="item.feeName"
            fold
            v-model:initFold="foldStatus[`fold${index}`]"
            :customContentStyle="{ padding: '0 24rpx 32rpx' }"
          >
            <template #status>
              <view class="status-button" :class="[item.feeStatus == 2 ? 'status-2' : '', item.feeStatus == 5 ? 'status-5' : '']">
                <text class="status-button-text">{{ item.feeStatusName }}</text>
              </view>
            </template>
            <ve-form-item label="应收款日" :prop="`orderFee.${index}.receivableTime`" required>
              <!-- 已收款 -->
              <template v-if="item.feeStatus == 2">
                {{ item.receivableTime || '-' }}
              </template>
              <ve-date-picker v-model="item.receivableTime" valueFormat="YYYY-MM-DD HH:mm:ss" mode="date" v-else />
            </ve-form-item>
            <ve-form-item label="完成付款时间">{{ item.confirmTime || '-' }}</ve-form-item>
            <ve-form-item label="每期应收金额" :prop="`orderFee.${index}.activeTotalAmount`" unit="元">
              <view class="stage-sum">{{ item.activeTotalAmount }}</view>
            </ve-form-item>
            <view class="fee-stage-block">
              <!-- 未收款 || 已驳回 -->
              <template v-if="item.feeStatus == 1 || item.feeStatus == 5">
                <stages-fee-edit :orderFeeIndex="index" />
              </template>
              <!-- 已收款 -->
              <template v-else-if="item.feeStatus == 2">
                <view v-for="(feeItem, feeIndex) in item.feeDetailList" :key="feeIndex">
                  <!-- type 为 1 代表为费用 -->
                  <ve-cell-val
                    v-if="feeItem.type == 1"
                    :label="feeItem.itemName"
                    :value="feeItem.costType == 20 ? -feeItem.amount : feeItem.amount"
                    unit="元"
                    :key="feeIndex"
                  />
                  <!-- type 为 0 代表目录 -->
                  <template v-else>
                    <ve-cell-val
                      :label="feeChildItem.itemName"
                      :value="feeChildItem.costType == 20 ? -feeChildItem.amount : feeChildItem.amount"
                      unit="元"
                      v-for="(feeChildItem, feeChildIndex) in feeItem.childrenList"
                      :key="feeChildIndex"
                    />
                  </template>
                </view>
              </template>
              <template v-else-if="item.feeStatus == 0">
                <stages-fee-pane
                  class="stages-fee-pane"
                  :feeTypeSwitch="false"
                  :orderFeeIndex="index"
                  :showStatistic="false"
                  :inlineCard="true"
                  :disabledOnlineFee="true"
                  :showViewPriceCalendarBtn="false"
                />
              </template>
              <!-- 存在 feeOption.remarkLabel 显示备注录入 -->
              <ve-form-item :borderBottom="false" label="备注" labelPosition="top">
                <ve-input type="textarea" placeholder="请输入备注" v-model="item.remark" :maxlength="200" />
              </ve-form-item>
            </view>
            <!-- 新增分期 -->
            <template v-if="index == feeForm.orderFee.length - 1">
              <!-- 删除本期 -->
              <!-- 未收款、已驳回支持删除 -->
              <ve-button
                class="stage-button"
                v-if="[0, 1, 5].includes(feeForm.orderFee[feeForm.orderFee.length - 1].feeStatus)"
                size="long"
                status="danger"
                type="plain"
                @click="deleteStageFn"
              >
                <template #icon>
                  <ve-icon name="delete" width="36" height="36" />
                </template>
                删除本期
              </ve-button>
            </template>
          </ve-card>
        </view>
        <!-- 添加新期数 -->
        <ve-button class="stage-button" size="long" :customStyle="{ backgroundColor: '#F3F7FF' }" type="plain" @click="addNewStageFn">
          <template #icon>
            <ve-icon name="plus" width="36" height="36" />
          </template>
          添加新期数
        </ve-button>
      </ve-form>
    </view>
    <footer-box id="footer-box">
      <template #extra>
        <div class="fee-summary">
          <div class="fee-summary-amount"
            >修改后租车总费用：<text class="amount">{{ feeSum }}</text
            ><text class="unit">元</text>
          </div>
          <div class="fee-summary-toggle" @click="viewFeeDetail"
            >查看详情<ve-icon class="icon" name="arrow-right" width="32" height="32" />
          </div>
        </div>
      </template>
      <ve-button type="primary" size="long" :loading="okLoading" @click="submitFn">确认</ve-button>
    </footer-box>
  </view>
</template>
<script setup>
  import { ref, provide, computed } from 'vue'
  import stagesFeePane from './components/edit-stages-fees/stages-fee-pane.vue'
  import stagesFeeEdit from './components/edit-stages-fees/stages-fee-edit.vue'
  import {
    buildCostInfoParam,
    getStoreTemplateDetail,
    compileFeeItemFromTemplate,
    getOrderFeeRules,
  } from './components/order-fee/fee-utils.js'
  import { czsOrderFeeDetailAPI, modifyOrderFeeAPI } from '@/api/order/lOrder'
  import footerBox from './form/components/footerBox.vue'
  import { cloneDeep } from '@/utils'
  import { onLoad } from '@dcloudio/uni-app'
  import useFormFold from '@/hooks/useFormFold'
  import useToast from '@/hooks/useToast'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'

  const feeForm = ref({
    orderFee: [],
  })

  const rules = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      let rule = {}
      // 应付款日必填
      orderFee.forEach((item, index) => {
        rule[`orderFee.${index}.receivableTime`] = [
          {
            required: true,
            message: '请选择应付款日',
          },
        ]
        rule[`orderFee.${index}.activeTotalAmount`] = [
          {
            validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback('每期应收金额需大于0')
              }
              callback()
            },
          },
        ]
      })

      // // 车辆租金必填
      // orderFee.forEach((item, index) => {
      //   if ([1, 5].includes(item.feeStatus)) {
      //     rule[`orderFee.${index}.feeDetailList.0.amount`] = [
      //       {
      //         required: true,
      //         message: '请输入金额',
      //       },
      //     ]
      //   }
      // })
      return {
        ...rule,
        ...getOrderFeeRules(orderFee),
      }
    } else {
      return {}
    }
  })
  provide('feeForm', feeForm)

  const { foldStatus, foldValidate, foldAddItem } = useFormFold([])
  const orderFeeId = ref()
  const orderInfo = ref({})
  const feeNameId = ref()
  onLoad((options) => {
    orderFeeId.value = options.id
    // 获取费用详情
    czsOrderFeeDetailAPI({ id: options.id }).then((res) => {
      const result = res.result
      const czsOrderFeeList = result.czsOrderFeeList
      feeNameId.value = czsOrderFeeList[0].feeNameId
      orderInfo.value = result.orderInfo
      feeForm.value.orderFee = czsOrderFeeList

      // 初始化第一次 fold
      czsOrderFeeList.forEach((item, index) => {
        foldAddItem({
          key: `fold${index}`,
          value: item.id == options.id ? true : false,
          props: [`orderFee.${index}.receivableTime`, `orderFee.${index}.activeTotalAmount`],
        })
      })
    })
  })
  const siteId = computed(() => {
    return orderInfo.value.siteId
  })
  const storeTemplate = ref()
  const priceTemplateId = ref()
  const getStoreTemplate = (cb) => {
    if (storeTemplate.value && priceTemplateId.value) {
      cb()
    } else {
      // 读取订单信息
      getStoreTemplateDetail(siteId.value, 2, (template, templateId) => {
        storeTemplate.value = template
        priceTemplateId.value = templateId
        cb()
      })
    }
  }
  // 添加新分期
  const addNewStageFn = () => {
    const list = feeForm.value.orderFee
    foldAddItem({
      key: `fold${list.length}`,
      value: true,
      props: [`orderFee.${list.length - 1}.receivableTime`, `orderFee.${list.length - 1}.feeDetailList.0.childrenList.${0}.amount`],
    })
    let feeName = ''
    // 租车费
    if (feeNameId.value == 1) {
      feeName = `租车费-第${list.length + 1}期`
    } else {
      feeName = `续租费-第${list.length + 1}期`
    }
    let newItem = {
      feeType: 1, // 线下费用
      feeName: feeName,
      feeNameId: feeNameId.value,
      activeTotalAmount: 0,
      readTemplate: true,
      feeDetailList: [],
      feeStatus: 0,
      feeStatusName: '未收款',
      feeDetailTypeList: ['basicStageFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
    }
    getStoreTemplate(() => {
      newItem.priceTemplateId = priceTemplateId.value
      compileFeeItemFromTemplate(newItem, storeTemplate.value)
      newItem.feeDetailList.forEach((item) => {
        delete item.remarkLabel
      })
      feeForm.value.orderFee.push(newItem)
    })
  }
  // 删除分期
  const deleteStageFn = () => {
    uni.showModal({
      title: '确认',
      content: '确认要删除当前分期吗？',
      success(res) {
        if (res.confirm) {
          let len = feeForm.value.orderFee.length - 1
          feeForm.value.orderFee.splice(len, 1)
        }
      },
    })
  }
  // 查看修改后详情
  const feeList = computed(() => {
    // name: '优惠券', value: 0, costType: 20
    // step1 生成汇总结构
    let feeDetailList = [
      {
        feeCategory: 0,
        statics: true,
        childrenList: [
          { itemName: '车辆租金', costType: 10, statics: true, amount: 0 },
          { itemName: '手续费', costType: 10, statics: true, amount: 0 },
          { itemName: '基础保险', costType: 10, statics: true, amount: 0 },
        ],
      },
      { feeCategory: 1, feeName: '增值服务费', statics: true, childrenList: [] },
      { feeCategory: 2, feeName: '优惠费用', statics: true, childrenList: [] },
      { feeCategory: 3, feeName: '其他费用', statics: true, childrenList: [] },
    ]
    // step2 遍历各个分期给结构赋值
    let orderFee = feeForm.value.orderFee
    orderFee.forEach((item) => {
      // 当前分期的费用合集
      let stageFeeDetailList = item.feeDetailList
      stageFeeDetailList.forEach((stageFeeItem) => {
        let targetFeeOption = feeDetailList.find((item) => item.feeCategory == stageFeeItem.feeCategory)
        // 类型为费用
        if (stageFeeItem.type == 1) {
          let findResult = targetFeeOption.childrenList.find((targetChildItem) => targetChildItem.itemName == stageFeeItem.itemName)
          findResult.amount += Number(stageFeeItem.amount)
        } else {
          // 类型为分类
          stageFeeItem.childrenList.forEach((stageFeeChildItem) => {
            const itemName = stageFeeChildItem.itemName
            const amount = stageFeeChildItem.amount
            if (amount > 0) {
              const costType = stageFeeChildItem.costType
              let findResult = targetFeeOption.childrenList.find((targetChildItem) => targetChildItem.itemName == itemName)
              if (findResult) {
                let resultCostType = findResult.costType
                if (resultCostType == costType) {
                  findResult.amount += amount
                } else {
                  // 合计为收款，当前项为付款
                  if (resultCostType == 10) {
                    findResult.amount = findResult.amount += -amount
                    if (Math.abs(amount) > findResult.amount) {
                      findResult.costType = 20
                    }
                  } else {
                    findResult.amount = findResult.amount += -amount
                    // 合计为付款
                    if (Math.abs(amount) > findResult.amount) {
                      findResult.costType = 10
                    }
                  }
                }
              } else {
                targetFeeOption.childrenList.push({
                  itemName,
                  amount,
                  costType,
                })
              }
            }
          })
        }
      })
    })
    // step3 将 itemName 转换成 name，并计算 有 childrenList 的 amount
    feeDetailList.forEach((item) => {
      if (item.feeCategory != 0) {
        if (item.childrenList.length > 0) {
          let sum = 0
          item.childrenList.forEach((childItem) => {
            sum += childItem.costType == 10 ? childItem.amount : -childItem.amount
          })
          item.amount = sum
        } else {
          item.amount = 0
        }
      }
    })
    // step4 转换结构
    let feeList = []
    for (let i = 0; i < feeDetailList.length; i++) {
      let item = feeDetailList[i]
      let childrenList = item.childrenList
      if (i == 0) {
        let tempList = childrenList.map((childItem) => {
          return {
            name: childItem.itemName,
            value: childItem.amount,
            costType: childItem.costType,
          }
        })
        feeList = tempList
      } else {
        let tempChidren = childrenList.map((childItem) => {
          return {
            name: childItem.itemName,
            value: childItem.costType == 20 ? -childItem.amount : childItem.amount,
            costType: childItem.costType,
          }
        })
        feeList.push({
          name: item.feeName,
          value: item.amount,
          children: tempChidren,
          childrenToggle: true,
        })
      }
    }
    return feeList
  })
  const feeSum = computed(() => {
    let sum = 0
    feeList.value?.forEach((item) => {
      sum += Number(item.value)
    })
    return sum
  })
  const viewFeeDetail = () => {
    let obj = {
      sum: feeSum.value,
      feeList: feeList.value,
    }
    // step5 计算sum
    // 存储到 storage 中，原费用信息页面不需要处理逻辑
    uni.setStorageSync('sOrderOriginFeeSumInfo', obj)
    uni.navigateTo({ url: '/pages/order/long-order/relet-order-origin-fee?title=修改后租车费用信息' })
  }
  // 对 orderFee 进行二次处理
  const handleOrderFee = (orderFee) => {
    let tempOrderFee = cloneDeep(orderFee)
    tempOrderFee.forEach((feeItem) => {
      let temp = []
      let feeDetailList = feeItem.feeDetailList
      let remark
      feeDetailList.forEach((feeDetailItem) => {
        let tempObj = {
          feeCategory: feeDetailItem.feeCategory,
          type: 1,
          ...feeDetailItem,
        }
        temp.push(tempObj)
        remark = feeDetailItem.remark
      })
      feeItem.remark = remark
      feeItem.feeDetailList = temp
    })
    return tempOrderFee
  }
  // 确认修改分期
  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = () => {
    if (feeForm.value.orderFee.length > 0) {
      formRef.value.validate((valid, erros) => {
        if (valid) {
          let orderFee = feeForm.value.orderFee
          let czsOrderFeeList = orderFee.map((orderFeeItem) => {
            if (orderFeeItem.feeStatus != 0) {
              // 对 feeDetailList 进行处理，费用为空则改为0
              orderFeeItem.feeDetailList.forEach((item) => {
                if (item.type == 1) {
                  if (!item.amount) item.amount = 0
                } else {
                  item.childrenList.forEach((childItem) => {
                    if (!childItem.amount) childItem.amount = 0
                  })
                }
              })
              return orderFeeItem
            } else {
              // 新增的分期
              let newStage = buildCostInfoParam({ orderFee: [orderFeeItem] })
              let newOrderFee = handleOrderFee(newStage.orderFee)
              return {
                ...newOrderFee[0],
                remark: orderFeeItem.remark,
              }
            }
          })
          const param = {
            id: orderFeeId.value,
            czsOrderFeeList: czsOrderFeeList,
          }
          okLoading.value = true
          modifyOrderFeeAPI(param)
            .then((res) => {
              useToast({
                title: '修改成功',
              }).then(() => {
                useLoadDataAndHotUpdateNavigateBack()
              })
            })
            .catch(() => {
              okLoading.value = false
            })
        } else {
          foldValidate(erros)
        }
      })
    } else {
      uni.showToast({
        title: '分期账单至少保留一期',
        icon: 'none',
        duration: 2000,
      })
    }
  }
</script>
<style lang="less" scoped>
  .container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    .fee-pane-content {
      padding: 24rpx;
      padding-bottom: 280rpx;
    }
  }

  .status-button {
    height: 40rpx;
    background: #fff7e8;
    border-radius: 1194rpx 1194rpx 1194rpx 1194rpx;
    border: 2rpx solid #ff7d00;
    font-size: 24rpx;
    font-weight: 500;
    color: #ff7d00;
    padding: 0 16rpx;
    display: flex;
    align-items: center;
    margin-left: 16rpx;
  }
  .status-2 {
    background: #e8f7ff;
    color: #3491fa;
    border: 2rpx solid #3491fa;
  }
  .status-5 {
    background: #ffece8ff;
    color: #f53f3fff;
    border: 2rpx solid #f53f3fff;
  }
  .stage-sum {
    font-size: 30rpx;
    color: #cdced0;
  }

  .fee-stage-block {
    background: #f6f7fbff;
    padding: 0 24rpx;
    /deep/ .ve-cell {
      padding: 32rpx 0 0;
    }

    /deep/ .ve-textarea {
      background-color: #eeeef0;
    }

    /deep/ .ve-card {
      background-color: unset;
      .choice-item {
        background: #eceef3;
      }
      .page-form-block {
        background-color: #eceef3;
      }
      .ve-card-header-title {
        font-size: 30rpx;
        font-weight: 400;
        color: #191c27;
      }
    }
  }
  .stages-fee-pane {
    /deep/ .generic-fee .ve-card-header-border-line + .ve-card-content {
      background-color: #eceef3;
      padding: 0 24rpx;
    }
  }
  .stage-button {
    margin-top: 32rpx;
  }
  #footer-box {
    height: 250rpx;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 100;
  }

  .fee-summary {
    display: flex;
    align-items: center;
    height: 112rpx;
    line-height: 110rpx;
    border-bottom: 2rpx solid rgba(216, 216, 216, 0.3);
    .fee-summary-amount {
      color: #1e1e1e;
      flex: 1;
      font-size: 28rpx;
      .amount {
        font-size: 48rpx;
        font-weight: 600;
        color: #fe615a;
      }
      .unit {
        color: #fe615aff;
        font-size: 24rpx;
        vertical-align: bottom;
        margin-left: 4rpx;
      }
    }
    .fee-summary-toggle {
      height: 44rpx;
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #3072f6;
      .icon {
        margin-left: 16rpx;
      }
    }
  }
  .stage-error {
    width: 100%;
    text-align: right;
    font-size: 26rpx;
    color: #f53f3f;
    line-height: 44rpx;
  }
</style>
